/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/Exceptions.hpp"
#include "VorbisSampler.hpp"

namespace XernVorbis
{
	VorbisSampler::VorbisSampler(const std::string &filename, FILE *oggFile)
		: filename(filename), oggFile(oggFile), vorbisInfo(NULL)
	{
		id = nil_uuid();

		// Open the stream.
		OpenStream();
	}

	VorbisSampler::VorbisSampler(const VorbisSampler &o)
		: vorbisInfo(NULL)
	{
		// Open the file.
		filename = o.filename;
		oggFile = fopen(o.filename.c_str(), "rb");
		assert(oggFile);

		// Open the stream.
		OpenStream();
	}

	VorbisSampler::~VorbisSampler()
	{
		if(oggFile)
			ov_clear(&oggStream);
	}

	void VorbisSampler::OpenStream()
	{
		// Open the ogg/vorbis stream.
		int res = ov_open(oggFile, &oggStream, NULL, 0);
		if(res < 0)
		{
			fclose(oggFile);
			oggFile = NULL;
			throw XernException("Failed to open ogg stream: " + ErrorString(res));
		}

		// Retrieve the stream information.
		vorbisInfo = ov_info(&oggStream,-1);
	}

	std::string VorbisSampler::ErrorString(int code)
	{
		switch(code)
		{
		case OV_ENOTVORBIS:
			return "Not vorbis data.";
		case OV_EBADHEADER:
			return "Invalid header.";
		default:
			return "Unknown ogg/vorbis error.";
		}
	}

	IResource::ResourceFlags VorbisSampler::GetFlags() const
	{
		return RFL_CASHEABLE;
	}

	void VorbisSampler::UpdateState(boost::shared_ptr<IDataFilter> stateData)
	{
	}

	const uuid &VorbisSampler::GetId() const
	{
		return this->id;
	}

	void VorbisSampler::SetId(const uuid &id)
	{
		this->id = id;
	}

	bool VorbisSampler::IsStreamed() const
	{
		return true;
	}

	unsigned int VorbisSampler::GetChannels() const
	{
		assert(vorbisInfo);
		return vorbisInfo->channels;
	}

	unsigned int VorbisSampler::GetSampleSize() const
	{
		return 2; // 16 bit, little endian
	}

	unsigned int VorbisSampler::GetSampleRate() const
	{
		return vorbisInfo->rate;
	}

	size_t VorbisSampler::GetSamples() const
	{
		return -1;
	}

	size_t VorbisSampler::Read(size_t bufferLen, void *buffer)
	{
		char *dest = (char*)buffer;
		size_t readed = 0;
		int section = 0;

		while(readed < bufferLen)
		{
			int res = ov_read(&oggStream, dest + readed, bufferLen - readed, 0, 2, 1, &section);
			if(res > 0)
				readed += res;
			else if (res == 0)
				break;
			else if(res < 0)
				throw XernException("Failed to read from the stream: " + ErrorString(res));
		}

		return readed;
	}

	void VorbisSampler::Rewind()
	{
		// Seek to the begining.
		ov_raw_seek(&oggStream, 0);
	}

	boost::shared_ptr<ISoundSampler> VorbisSampler::Clone() const
	{
		boost::shared_ptr<ISoundSampler> ret(new VorbisSampler(*this));
		return ret;
	}

} // namespace XernVorbis
